import {
  getSubjectList,
  getMerchantSubjectList,
  addMerchantSubject,
  delMerchantSubject,
} from "@/common/apis/goods";
import store from "@/store";

const state = {
  subjectList: uni.getStorageSync("subjectList") || [],
  merchantSubjectList: uni.getStorageSync("merchantSubjectList") || [],
};

const getters = {
  formatSubjectList: (state) => {
    if (store.state.user.isStore) {
      return state.merchantSubjectList;
    } else {
      return state.subjectList;
    }
  },
};

const mutations = {
  UPDATE_SUBJECT_SEQUENCE(state, list) {
    state.subjectList = list;
    uni.setStorageSync("subjectList", list);
  },
  UPDATE_MERCHANT_SUBJECT_SEQUENCE(state, list) {
    state.merchantSubjectList = list;
    uni.setStorageSync("merchantSubjectList", list);
  },
};

const actions = {
  updateSubjectSequence({ commit }, list) {
    commit("UPDATE_SUBJECT_SEQUENCE", list);
  },
  updateMerchantSubjectSequence({ commit }, list) {
    commit("UPDATE_MERCHANT_SUBJECT_SEQUENCE", list);
  },
  fetchSubjectList({ commit }) {
    return new Promise((resolve, reject) => {
      getSubjectList().then((res) => {
        commit("UPDATE_SUBJECT_SEQUENCE", res);
        resolve(res);
      });
    });
  },
  fetchMerchantSubjectList({ commit }, id) {
    return new Promise((resolve, reject) => {
      getMerchantSubjectList(id).then((res) => {
        commit("UPDATE_MERCHANT_SUBJECT_SEQUENCE", res);
        resolve(res);
      });
    });
  },
  // 添加商户分类
  fetchAddMerchantSubject({ commit }, subject_id) {
    return new Promise((resolve, reject) => {
      addMerchantSubject({ subject_id }).then((res) => {
        resolve(res);
      });
    });
  },
  // 删除商户分类
  fetchDelMerchantSubject({ commit }, subject_id) {
    return new Promise((resolve, reject) => {
      delMerchantSubject({ subject_id }).then((res) => {
        resolve(res);
      });
    });
  },
};

export default {
  state,
  getters,
  mutations,
  actions,
};
